import 'dart:math';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'package:ball_lion/entity/expert/zq_hot_expert_entity.dart';
import 'package:ball_lion/module/expert/items/league_hot_expert.dart';
import 'package:ball_lion/module/match/detail/match_views_logic.dart';
import 'package:ball_lion/module/expert/items/plan_item.dart';
import 'package:ball_lion/module/pick/items/expert_record_tag.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/widgets/ads_label.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/choice_bar.dart';
import 'package:ball_lion/widgets/card.dart';
import 'package:ball_lion/widgets/ladder_tab_bar.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';

class MatchViewsPage extends StatefulWidget {
  const MatchViewsPage({super.key, this.matchId});

  final int? matchId;

  @override
  State<MatchViewsPage> createState() => _MatchViewsPageState();
}

class _MatchViewsPageState extends State<MatchViewsPage>
    with AutomaticKeepAliveClientMixin {
  late MatchViewsLogic logic;
  int random = Random().nextInt(10000);

  @override
  void initState() {
    logic = Get.put(MatchViewsLogic(), tag: '${widget.matchId}$random');
    logic.matchId = "${widget.matchId}";
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<MatchViewsLogic>(
        tag: '${widget.matchId}$random',
        builder: (logic) {
          return logic.tabController == null
              ? Container()
              : Column(children: [
                  Container(
                    color: Colours.white,
                    padding: const EdgeInsets.symmetric(vertical: 5),
                    child: ChoiceBar(
                      initialIndex: logic.tabIndex,
                      items: logic.tabs,
                      backgroundColor: Colours.redFEECEC,
                      textColor: Colours.main,
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      onTap: (index) {
                        Utils.onEvent('bsxq',
                            params: {'bsxq': '${index + 13}'});
                        logic.tabIndex = index;
                        logic.getData(index);
                        logic.refreshController.resetFooter();
                      },
                    ),
                  ),
                  Expanded(child: _buildPage()),
                ]);
        });
  }

  Widget _buildPage() {
    return EasyRefresh.builder(
        header: Styles.refreshHeader(position: IndicatorPosition.locator),
        footer: Styles.refreshFooter(position: IndicatorPosition.locator),
        controller: logic.refreshController,
        onRefresh: logic.getRefresh,
        onLoad: logic.loadMore,
        childBuilder: (context, physics) {
          return TabBarView(
              physics: const NeverScrollableScrollPhysics(),
              controller: logic.tabController,
              children: List.generate(
                  logic.pages.length, (index) => _buildList(physics, index)));
        });
  }

  Widget _buildList(physics, int index) {
    return CustomScrollView(
      physics: physics,
      slivers: [
        const HeaderLocator.sliver(),
        SliverToBoxAdapter(
            child: AdsLabel(
          adsTag: "match_${logic.sportsId == 1 ? "zq" : "lq"}_观点_$index",
          tapType: 'match_detail_plan_advertising',
          margin: const EdgeInsets.fromLTRB(8, 8, 8, 0),
        )),
        if (index == 1 && logic.boardController != null)
          SliverToBoxAdapter(
              child: HotExpertBoard(
            controller: logic.boardController!,
          ).paddingOnly(top: 8, left: 8, right: 8)),
        LoadingWidget<bool>(
            isLoading: false,
            data: User.info == null && index == 0,
            noData: NoDataWidget.sliver(
                physics: physics,
                tip: "请登录后查看",
                buttonText: "去登录",
                onTap: () => User.needLogin(() async => logic.getData(0))),
            child: () => LoadingWidget<bool>(
                isLoading: logic.pages[index].items == null,
                loading: const SliverToBoxAdapter(),
                data: logic.pages[index].items?.length == 0,
                noData: NoDataWidget.sliver(
                    physics: physics, tip: "暂无${index == 2 ? "免费" : "相关"}方案"),
                child: () => SliverList(
                    delegate: SliverChildBuilderDelegate(
                        childCount: logic.pages[index].items?.length ?? 0,
                        (context, p) => Block(
                            cardStyle: const CardStyle(
                                padding: EdgeInsets.symmetric(horizontal: 12),
                                margin: EdgeInsets.fromLTRB(8, 8, 8, 0)),
                            child: PlanItem(
                              isMatchView: true,
                              entity: logic.pages[index].items![p],
                              eventType: "match_detail_plan_view",
                            )))))),
        const FooterLocator.sliver()
      ],
    );
  }

  Widget hotExpert() {
    return Block(
        cardStyle: const CardStyle(
            margin: EdgeInsets.fromLTRB(8, 10, 8, 0),
            gradient: LinearGradient(
                colors: [Colours.redF53F3F, Colours.redFFDCDC],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter)),
        child: Padding(
          padding: const EdgeInsets.all(4),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                width: Get.width,
                child: Stack(
                  alignment: Alignment.centerLeft,
                  children: [
                    LadderTabBar(
                        tabs: [QsText("${logic.leagueName}专家榜")],
                        selectLabelStyle: TabStyle(color: Colours.text),
                        labelStyle: TabStyle(
                            color: Colours.white, weight: FontWeight.w600),
                        needEnd: false,
                        scrollable: true,
                        keepSize: false,
                        labelPadding:
                            const EdgeInsets.symmetric(horizontal: 10)),
                    Positioned(
                        right: 4,
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            const QsText("更多专家",
                                fontSize: 12, color: Colours.white),
                            Image.asset(
                              Utils.getImgPath("arrow_right_48.png"),
                              width: 16,
                              color: Colours.white,
                            )
                          ],
                        ).tap(() => Get.toNamed(Routes.expertTop,
                            arguments: logic.sportsId - 1,
                            parameters: {"onlySale": "1"})))
                  ],
                ),
              ),
              Container(
                clipBehavior: Clip.antiAlias,
                padding: const EdgeInsets.symmetric(vertical: 12),
                decoration: BoxDecoration(
                    color: Colours.white,
                    border: Border.all(color: Colours.white, width: 0),
                    borderRadius: const BorderRadius.only(
                        topLeft: Radius.circular(0),
                        topRight: Radius.circular(8),
                        bottomLeft: Radius.circular(8),
                        bottomRight: Radius.circular(8))),
                child: GridView.count(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  crossAxisCount: 5,
                  mainAxisSpacing: 12,
                  padding: EdgeInsets.zero,
                  childAspectRatio: 1 / 1.15,
                  children: List.generate(logic.expertTop?.length ?? 0,
                      (i) => hotExpertItem(logic.expertTop?[i], i)),
                ),
              )
            ],
          ),
        ));
  }

  Widget hotExpertItem(HotExpertEntity? entity, int index) {
    return GestureDetector(
      onTap: () {
        // Utils.onEvent('cjrmzj',params: {'cjrmzj':index});
        Get.toNamed(Routes.userPage, arguments: entity?.userId, parameters: {
          'type': '1',
          'index': logic.sportsId == 1 ? 'zq' : 'lq'
        });
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: [
          Stack(
            children: [
              Container(
                clipBehavior: Clip.antiAlias,
                decoration: BoxDecoration(
                    border: Border.all(
                        color: Colours.greyEE,
                        width: 0.5,
                        strokeAlign: BorderSide.strokeAlignOutside),
                    shape: BoxShape.circle),
                child: CachedNetworkImage(
                    fit: BoxFit.cover,
                    width: 40,
                    height: 40,
                    placeholder: (context, url) => Container(),
                    errorWidget: (context, url, error) => Container(),
                    imageUrl: entity?.logo ?? ''),
              ),
              if (entity?.viewCnt.hasValue == true)
                Positioned(
                  top: 0,
                  right: 0,
                  child: Container(
                      width: 13,
                      height: 13,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          gradient: const LinearGradient(
                              colors: [Color(0xFFF54D4F), Color(0xFFF53C6A)],
                              begin: AlignmentDirectional.topCenter,
                              end: Alignment.bottomCenter),
                          shape: BoxShape.circle,
                          border: Border.all(color: Colors.white, width: 0.5)),
                      child: QsText("${entity?.viewCnt ?? ""}",
                          needCenter: true,
                          fontSize: 10,
                          color: Colours.white)),
                )
            ],
          ),
          const SizedBox(height: 4, width: 10),
          QsText(
            entity?.name ?? '',
            fontSize: 12,
            fontWeight: FontWeight.w500,
            maxLines: 1,
          ),
          const SizedBox(height: 3, width: 10),
          ExpertRecordTag(
            text: entity?.value,
            type: 6,
            textSize: 10,
          ).paddingSymmetric(horizontal: 2)
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
